﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Lib.Core
{
    public class MathHelper
    {
        public static Point GetCrossPoint(Point[] line1, Point[] line2)  //计算两条直线的交点。直线由整数向量形式提供。
        {
            var pt = GetCrossPoint(new PointF[] { line1[0], line1[1] }, new PointF[] { line2[0], line2[1] });

            return new Point((int)pt.X, (int)pt.Y);
        }

        public static PointF GetCrossPoint(PointF[] line1, PointF[] line2)  //计算两条直线的交点。直线由整数向量形式提供。
        {

            PointF pt = new PointF();
            float k1, k2, b1, b2;

            if (line1[0].X == line1[1].X)//如果第一条直线斜率不存在
            {
                pt.X = line1[0].X;

                pt.Y = line2[0].Y == line2[1].Y ? line2[1].Y :

                        (float)((line2[0].Y - line2[1].Y) * (pt.X - line2[0].X) / (line2[0].X - line2[1].X) + line2[0].Y);

            }
            else if (line2[0].X == line2[1].X)//如果第二条直线斜率不存在
            {
                pt.X = line2[0].X;

                pt.Y = line1[0].Y == line1[1].Y ? line1[0].Y :

                        (float)((line1[0].Y - line1[1].Y) * (pt.X - line1[0].X) / (line1[0].X - line1[1].X) + line1[0].Y);
            }
            else     //求出斜截式方程。然后让k1x + b1 = k2x + b2，解出x，再算出y即可
            {
                k1 = (float)((line1[1].Y - line1[0].Y) / (line1[1].X - line1[0].X));
                b1 = (float)((line1[0].Y - k1 * line1[0].X));

                k2 = (float)((line2[1].Y - line2[0].Y) / (line2[1].X - line2[0].X));
                b2 = (float)((line2[0].Y - k2 * line2[0].X));

                pt.X = (b2 - b1) / (k1 - k2);  //算出x

                pt.Y = k1 * pt.X + b1; //算出y

            }

            return pt;

        }

        public static Point GetYaxisPoint(Point[] line1)
        {
            var pt = GetYaxisPoint(new PointF[] { line1[0], line1[1] });

            return new Point(0, (int)pt.Y);
        }

        public static PointF GetYaxisPoint(PointF[] line1)
        {
            var k1 = (float)((line1[1].Y - line1[0].Y) / (line1[1].X - line1[0].X));
            var b1 = (float)((line1[0].Y - k1 * line1[0].X));
            var y = k1 * 0 + b1;
            return new PointF(0, y);
        }
    }
}
